package com.ccl.iot.managers;import java.util.ArrayList;

import android.content.Context;

import com.ccl.iot.IOTObject.IOTListObject;

public abstract class ListedManager<TYPE> extends Manager implements IOTListObject<TYPE>{
	private ArrayList<IOTListChangeListener<TYPE>> iListChangeListeners = null;
	
	ListedManager(Context aContext) {
		super(aContext);
	}

	@Override
	public long getID() {
		return this.hashCode();
	}
	
	public int getListChangeListenerCount(){
		return iListChangeListeners == null ? 0 : iListChangeListeners.size();
	}

	@Override
	public boolean addListChangeListener(IOTListChangeListener<TYPE> aListener) {
		if (aListener != null){
			if (iListChangeListeners == null){
				iListChangeListeners = new ArrayList<IOTListChangeListener<TYPE>>();
			}else if (iListChangeListeners.contains(aListener)){
				return false;
			}
			
			return iListChangeListeners.add(aListener);
		}
		
		return false;
	}

	@Override
	public boolean removeListChangeListener(IOTListChangeListener<TYPE> aListener) {
		if (aListener != null){
			if (iListChangeListeners != null){
				return iListChangeListeners.remove(aListener);
			}
		}
		
		return false;
	}
	
	protected void onNewObject(TYPE aObject) {
		if (iListChangeListeners != null && aObject != null){
			IOTListChangeListener<TYPE> tListener;
			
			for (int i = 0; i < iListChangeListeners.size(); i++){
				if ((tListener = iListChangeListeners.get(i)) != null){
					tListener.onNewObject(this, aObject);
				}
			}
		}
	}

	protected void onObjectRemoved(TYPE aObject) {
		if (iListChangeListeners != null && aObject != null){
			IOTListChangeListener<TYPE> tListener;
			
			for (int i = 0, tCount = iListChangeListeners.size(); i < tCount; i++){
				if ((tListener = iListChangeListeners.get(i)) != null){
					tListener.onObjectRemoved(this, aObject);
				}
			}
		}
	}
}
